package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SkuSearchController {

    @Reference
    private SkuSearchService skuSearchServiceI;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {
        searchMap= WebUtil.convertCharsetToUTF8(searchMap);
        if (searchMap.get("pageNo") == null) {
            searchMap.put("pageNo", "1");
        }
        // 页面传递给后端 两个参数  sort:排序字段  sortOrder  排序规则（升序/降序）
        if(searchMap.get("sort") == null){  //排序字段
            searchMap.put("sort", "");
        }
        if(searchMap.get("sortOrder") == null){ //排序规则
            searchMap.put("sortOrder", "DESC");
        }

        Map result = skuSearchServiceI.search(searchMap);

        model.addAttribute("result", result);
        //url处理
        StringBuffer url=new StringBuffer("/search.do?");
        boolean flag = true;
        for(String key:searchMap.keySet()){

            if (flag) {
                url.append(key+"="+searchMap.get(key) );
            } else {
                url.append("&" + key+"="+searchMap.get(key) );
            }
            flag = false;
        }
        model.addAttribute("url", url);
        model.addAttribute("searchMap", searchMap);
        int startPage = 0;
        int endPage = 0;
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        Long totalPages = (Long)result.get("totalPages");
        if (totalPages <= 5) {
            startPage = 1;
            endPage = totalPages.intValue();
        } else {
            startPage = pageNo - 2;
            if (startPage <= 0) {
                startPage = 1;
            }
            endPage = startPage + 4;
            // 6 7 8 9 10
            if (pageNo + 2 >totalPages.intValue()) {
                startPage = totalPages.intValue() - 4;
                endPage = totalPages.intValue();
            }
        }
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);
        return "search";
    }





}
